package com.kgd.news.utils.wx;

import com.alibaba.fastjson.JSON;
import com.jfinal.plugin.activerecord.Db;
import com.kgd.news.bean.TemplateData;
import com.kgd.news.bean.VideoInfoModel;
import com.kgd.news.bean.WeChatTemplate;
import com.kgd.news.entity.SysDict;
import com.kgd.news.entity.Xcxmessage;
import com.kgd.news.utils.Config;
import com.kgd.news.utils.Constants;
import com.kgd.news.utils.FileHelper;
import com.kgd.news.utils.StringUtilsWx;
import okhttp3.*;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Email: huangsanm@foxmail.com
 * @Date: 2017/8/14
 * @Time: 下午8:35
 */
public class WxHelper {
    public final static String GET_OPEN_ID = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
    //    最新爆笑视频集
//    如果不是常量是静态变量的话，可能会被回收吗
    public static String APPID_C = "";
    public static String AppSecret_C = "";
    public static String accessToken;
    public static long accessTokenTime = 0L;
    public static OkHttpClient client = new OkHttpClient();


    /**
     * 获取opendi
     *
     * @param code
     * @return
     */
    public static String requestWxOpenId(String code) {
        try {
            String url = String.format(GET_OPEN_ID, getAppId(), getAppSecret(), code);
            Request request = new Request.Builder().get().url(url).build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            System.out.println("result:::" + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getAppSecret() {
        if (StringUtilsWx.isEmpty(AppSecret_C)) {
            AppSecret_C = Config.getPropertiesValue("init.properties","AppSecret_C");
            return AppSecret_C;
        }
        return AppSecret_C;
    }

    public static String getAppId() {
        if (StringUtilsWx.isEmpty(APPID_C)) {
            APPID_C = Config.getPropertiesValue("init.properties","APPID_C");
            return APPID_C;
        }
        return APPID_C;
    }

    /**
     * 获取opendi
     * @return
     */
    public static String requestUrl(String url) {
        try {
            Request request = new Request.Builder().get().url(url).build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            System.out.println("requestUrlresult:::" + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取opendi
     * @return
     */
    public static Response requestUrl(String url,String requestMethod, String output ) {
        try {
            Request request;
            if ("POST".equals(requestMethod)) {
                RequestBody requestBodyPost = RequestBody.create(MediaType
                        .parse("application/json"), output==null?"":output);
                request = new Request.Builder().post(requestBodyPost).url(url).build();
            } else {
                request = new Request.Builder().get().url(url).build();
            }

            Response response = client.newCall(request).execute();
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @return
     */
    public static String  requestUrlPostDownload(String url, Map<String, Object> t, HttpServletRequest request, String page) {
        FileOutputStream fos = null;
        InputStream inputStream = null;
        try {
            String jsonString = JSON.toJSONString(t);
            String qrName = page.replace("/", "") + getAppId() + ".png";
            File file = new File(Config.getFileBasePath() + qrName);
            if (file.exists()) {
                return FileHelper.getFileVituralPath(request,qrName);
            }
            RequestBody requestBodyPost = RequestBody.create(MediaType
                    .parse("application/json"), jsonString);
            Request requestPost = new Request.Builder()
                    .url(url)
                    .post(requestBodyPost)
                    .build();
            Response response = client.newCall(requestPost).execute();
            if (response.code() == 200) {
                long total = response.body().contentLength();
//                如果是出错的话，total大概69左右
                if (total > 1000) {
                    inputStream = response.body().byteStream();
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    fos = new FileOutputStream(file);
                    int len = 0;
                    byte[] buf = new byte[2048];
//                buf缓存区，每次拿到数据，len记录这次读了多少数据
                    while ((len = inputStream.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                    return FileHelper.getFileVituralPath(request, qrName);
                } else {
                    inputStream = response.body().byteStream();
                 String text=   inputStream2String(inputStream);
                    return text;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public   static   String   inputStream2String(InputStream   is)   throws   IOException{
        ByteArrayOutputStream   baos   =   new   ByteArrayOutputStream();
        int   i=-1;
        while((i=is.read())!=-1){
            baos.write(i);
        }
        return   baos.toString();
    }


    private static String createFileWithByte(byte[] bytes, File file) {
        // TODO Auto-generated method stub
        /**
         * 创建File对象，其中包含文件所在的目录以及文件的命名
         */
        // 创建FileOutputStream对象
        FileOutputStream outputStream = null;
        // 创建BufferedOutputStream对象
        BufferedOutputStream bufferedOutputStream = null;
        try {
            // 获取FileOutputStream对象
            outputStream = new FileOutputStream(file);
            // 获取BufferedOutputStream对象
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            // 往文件所在的缓冲输出流中写byte数据
            bufferedOutputStream.write(bytes);
            // 刷出缓冲输出流，该步很关键，要是不执行flush()方法，那么文件的内容是空的。
            bufferedOutputStream.flush();
            return "";
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            return null;
        } finally {
            // 关闭创建的流对象
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
    }

    /**
     *
     * @return
     */
    public static String requestAccessToke() {
        if (!StringUtilsWx.isEmpty(accessToken)) {
            if (System.currentTimeMillis() - accessTokenTime < 2 * 59 * 60 * 1000L) {
                return accessToken;
            }
        }
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + getAppId() + "&secret=" + getAppSecret();
        try {
            Request request = new Request.Builder().get().url(url).build();
            Response response = client.newCall(request).execute();
            String accessTokeJson = response.body().string();
            if (!StringUtilsWx.isEmpty(accessTokeJson)) {
                String access_token = JSON.parseObject(accessTokeJson).getString("access_token");
                System.out.println("requestUrlresult:::" + access_token);
                accessTokenTime = System.currentTimeMillis();
                accessToken = access_token;
                return access_token;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * @param url
     * @param xcxmessage
     * @param videoInfoModel
     * @param page
     */
    public static void sentTemplateMessage(String url, Xcxmessage xcxmessage, VideoInfoModel videoInfoModel, String page) {
        WeChatTemplate weChatTemplate = new WeChatTemplate();
        weChatTemplate.setTouser(xcxmessage.getOpenid());
        weChatTemplate.setForm_id(xcxmessage.getFormid());
        if (!StringUtilsWx.isEmpty(page)) {
            weChatTemplate.setPage(page);
        }
        SysDict sysDict = SysDict.dao.findFirst("select * from sys_dict where name =\"影视更新模版ID\"");
        String templateId = "bWnlcp0MnVyW-styndrvqbgcfqnFe97Z5_yqwyJ3DkA";
        if (sysDict != null) {
            templateId = sysDict.getDValue();
        }
        weChatTemplate.setTemplate_id(templateId);

        if (videoInfoModel != null) {
            //模板数据
            Map<String, TemplateData> data = new HashMap<String, TemplateData>();
            data.put("keyword1", new TemplateData(videoInfoModel.getKeyword1(), "#173177"));
            data.put("keyword2", new TemplateData(videoInfoModel.getKeyword2(), "#173177"));
            if (!StringUtilsWx.isEmpty(videoInfoModel.getKeyword3())) {
                data.put("keyword3", new TemplateData(videoInfoModel.getKeyword3(), "#173177"));
            } else {
                data.put("keyword3", new TemplateData(new SimpleDateFormat("yyyy年MM月dd日 HH时").format(new Date()), "#173177"));
            }
            data.put("keyword4", new TemplateData(videoInfoModel.getKeyword4(), "#173177"));
            weChatTemplate.setData(data);
        }

        RequestBody requestBodyPost = RequestBody.create(MediaType
                .parse("application/json"), JSON.toJSONString(weChatTemplate));
        Request requestPost = new Request.Builder()
                .url(url)
                .post(requestBodyPost)
                .build();
        client.newCall(requestPost).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.e("sentTemplateMessage,fail");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();
            }
        });
    }

    public static int sendTemplate(VideoInfoModel videoInfoModel, String page, String color) {
        long cutTime = System.currentTimeMillis() - 7 * 24 * 60 * 1000 * 60L;
        int count = 0;
//
        List<Xcxmessage> xcxmessageList = Xcxmessage.dao.find("select * from xcxmessage where createtime > " + cutTime + " group by openid");
        String access_token = WxHelper.requestAccessToke();
        if (!StringUtilsWx.isEmpty(access_token)) {
            String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + access_token;
            for (Xcxmessage xcxmessage :
                    xcxmessageList) {
                WxHelper.sentTemplateMessage(url, xcxmessage, videoInfoModel, page);
//                如果有问题的话，就不去删除了吧，如果失败的话，也就不去删除了吧。
//                xcxmessage.dao().deleteById(xcxmessage.getId());
                Db.update("delete from xcxmessage where id = " + xcxmessage.getId());
                count++;
            }
        }
        return count;
    }

    public static String getQrCodeB(HttpServletRequest request) {

        SysDict sysDict = SysDict.dao.findFirst("select * from sys_dict where name =\"二维码页面\"");
//        {"msg":"{\"errcode\":41030,\"errmsg\":\"invalid page hint: [.BGIOa06291540]\"}","code":204,"data":{}}错误
//        小程序上线之后就可以了，开发版和体验版都不行的
        String page = "pages/img/img";
        if (sysDict != null) {
            page = sysDict.getDValue();
        }
//        本地有没有二维码图片，二维码图片
        String accessToke = requestAccessToke();
        if (!StringUtilsWx.isEmpty(accessToke)) {
            Map<String, Object> param = new HashMap<>();
            param.put("page", page);
            param.put("width", 430);
            param.put("auto_color", false);
            param.put("scene", "scenenenenen");
            Map<String, Object> line_color = new HashMap<>();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            param.put("line_color", line_color);
            return requestUrlPostDownload(Constants.QRCODE_B + accessToke, param, request, page);
        }
        return null;
    }
}
